const router = require("koa-router")();
const MovieModel = require("../../models/movie");
const UserModel = require("../../models/users")
router.post("/api/movieCollect", async ctx => {
    // let { m } = ctx.request.params;//要更改的集合
    let { id, collected } = ctx.request.body;//要更改的集合的某个值
    console.log(id,collected);
    var table = ["top250","inTheaters","comingSoon"];
    for(let m of table){
        console.log(m);
        try {
            // 这里m传入不存在的合集名字时，会继续向下运行，但是data值为空。而id或者collected值不存在就会走catch；
            var data = await MovieModel(m).findByIdAndUpdate({ _id: id }, { $set: { collected } });
            console.log(data);
            if (data) {
                var newData = await MovieModel(m).find({_id:id})
                if(collected){
                    await UserModel.updateOne({}, { $push: { collectsMovies: newData } });
                    ctx.body = {
                        code: 200,
                        result: newData,
                        msg: "收藏成功！"
                    }
                }else{
                    await UserModel.updateOne({}, { $pull: { collectsMovies: {_id:id} } });
                    ctx.body = {
                        code: 200,
                        result: data,
                        msg: "取消收藏"
                    }
                }
            } else {
                ctx.body = {
                    code: 400,
                    msg: "请求的合集不存在"
                }
            }
        } catch (err) {
            ctx.body = {
                code: 400,
                msg: "参数不合法！"
            }
        }
    }
})
module.exports = router;